﻿
namespace BackupLib.Remoting
{
    using System;

    /// <summary>
    /// Event Sink Class used in subscription.
    /// The event handlers in this class are marshaled to the remote object
    /// The delegate within this call can be used by the local object intending
    /// to get the event.
    /// </summary>
    [Serializable]
    public class BackupEventSink : MarshalByRefObject, IDisposable
    {
        /// <summary>
        /// Occurs when the server publishes a subscribed event.
        /// </summary>
        public event EventHandler<BackupFileEventArgs> OnFile;
        public event EventHandler<BackupEventArgs> OnStart;
        public event EventHandler<BackupFinishedEventArgs> OnStop;

        private IBackupTask RemoteObject;

        public BackupEventSink(IBackupTask remoteObject)
        {
            RemoteObject = remoteObject;
            remoteObject.OnFile += RemoteOnFile;
            remoteObject.OnStart += RemoteOnStart;
            remoteObject.OnStop += RemoteOnStop;
        }

        public void RemoteOnFile(object sender, BackupFileEventArgs e)
        {
            if (OnFile != null)
                OnFile(sender, e);
        }

        public void RemoteOnStart(object sender, BackupEventArgs e)
        {
            if (OnStart != null)
                OnStart(sender, e);
        }

        public void RemoteOnStop(object sender, BackupFinishedEventArgs e)
        {
            if (OnStop != null)
                OnStop(sender, e);
        }

        /// <summary>
        /// Overriding the base class method to make the object live "forever"
        /// </summary>
        /// <returns>null</returns>
        public override object InitializeLifetimeService()
        {
            return null;
        }

        public void Dispose()
        {
            RemoteObject.OnFile -= RemoteOnFile;
            RemoteObject.OnStart -= RemoteOnStart;
            RemoteObject.OnStop -= RemoteOnStop;
        }
    }
}
